package com.letv.core.network.volley;

import java.util.concurrent.BlockingQueue;

import android.os.Process;

import com.letv.core.network.volley.listener.ResponseDelivery;

/**
 * 缓存调度器
 * 
 * @author zhuqiao
 * 
 */
public class CacheDispatcher extends Thread {
    private final ResponseDelivery mDelivery;
    private final BlockingQueue<VolleyRequest<?>> mCacheQueue;// 缓存请求队列
    private final BlockingQueue<VolleyRequest<?>> mNetworkQueue;// 网络请求队列

    private volatile boolean mQuit = false;

    public CacheDispatcher(BlockingQueue<VolleyRequest<?>> cacheQueue, BlockingQueue<VolleyRequest<?>> networkQueue,
            ResponseDelivery delivery) {
        mDelivery = delivery;
        mCacheQueue = cacheQueue;
        mNetworkQueue = networkQueue;
    }

    public void quit() {
        mQuit = true;
        // 通知线程中断
        interrupt();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

        while (true) {
            try {
                final VolleyRequest<?> request = mCacheQueue.take();

                new CacheRequestData(mDelivery, false).start(request);
            } catch (InterruptedException e) {
                if (mQuit) {
                    return;
                }
                continue;
            }
        }
    }

}
